<template>
  <a-spin class="table-gl-con" style="margin-top: 0" :loading="submitLoading">
    <TableWrap style="flex: 1" @refresh="getTableList">
      <template #headerLeft>
        <a-space>
          <p>共计 {{ total }} 条</p>
          <a-button type="primary" size="medium" @click="addNegativeKeyword" v-if="$authPass('negativeKeyword.create')">添加</a-button>
          <a-button class="gray-outline" size="medium" @click="changeStatus('ARCHIVED')" v-if="$authPass('negativeKeyword.adjust')">归档</a-button>
          <a-button class="gray-outline" size="medium" @click="batchAddOtherNegativeKeyword" v-if="$authPass('negativeKeyword.create')">批量添加到其他否定</a-button>
          <div>
            <span>已选</span>
            <span class="highlight" style="margin-left: 10px">{{ selectIds.length }}</span>
          </div>
          <a-button type="text" size="medium" @click="clearSelect">清除已选</a-button>
        </a-space>
      </template>
      <template #tableBody>
        <a-table
          class="table-singe-line"
          ref="tableRef"
          row-key="id"
          :loading="tableLoading"
          @selection-change="selectColumn"
          :row-selection="rowSelection"
          :bordered="false"
          :data="tableList"
          :scroll="{
            y: '100%',
          }"
          size="mini"
          @sorter-change="sorterChange"
          :pagination="false"
        >
          <template #columns>
            <a-table-column :width="160" data-index="keywordText" title="否定关键词" />
            <a-table-column :width="70" title="否定状态">
              <template #cell="{ record }">
                <p :class="$extract(statusMap[record.state], 'color')">{{ $extract(statusMap[record.state], 'name') }}</p>
              </template>
            </a-table-column>
            <a-table-column :width="80" title="匹配类型">
              <template #cell="{ record }">
                <p>{{ NegativeKeywordMatchType[record.matchType] || record.matchType }} </p>
              </template>
            </a-table-column>
            <a-table-column :width="140" title="店铺" data-index="shopName" />
            <a-table-column :width="100" title="广告组合" data-index="portfolioName">
              <template #cell="{ record }">
                <p :class="props.level ? '' : 'highlight cursor'" @click="toPortfolioDetail(record)">{{ record.portfolioName }}</p>
              </template>
            </a-table-column>
            <a-table-column :width="140" title="广告活动" data-index="campaignName">
              <template #cell="{ record }">
                <p :class="props.level ? '' : 'highlight cursor'" @click="toCampaignDetail(record)">{{ record.campaignName }}</p>
              </template>
            </a-table-column>
            <a-table-column :width="140" title="广告组" data-index="adGroupName">
              <template #cell="{ record }">
                <p :class="props.level ? '' : 'highlight cursor'" @click="toAdGroupDetail(record)">{{ record.adGroupName }}</p>
              </template>
            </a-table-column>
            <a-table-column :width="140" title="创建时间" :sortable="sortable" data-index="creationDateTime">
              <template #cell="{ record }">
                <p>{{ $setTime(record.creationDateTime) }}</p>
              </template>
            </a-table-column>
            <a-table-column :width="60" title="操作">
              <template #cell="{ record }">
                <a-popconfirm v-if="$authPass('negativeKeyword.adjust')" content="确定是否归档该否定关键词" @ok="requestUpdataState([record], 'ARCHIVED')" type="warning">
                  <a-button v-if="record.state != 'ARCHIVED'" type="text">归档</a-button>
                </a-popconfirm>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
    </TableWrap>
    <div class="pagination-footer">
      <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 300]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
    </div>
  </a-spin>
  <!-- 添加否定关键词 -->
  <AddNegativeKeyword v-if="showAddNegativeKeyword" :level="level" :type="addType" :isShow="showAddNegativeKeyword" :shopList="shopList" :defaultVal="defaultVal" @closed="showAddNegativeKeyword = false" @success="getTableList" />
</template>
<script lang="ts" setup>
  import { ref, reactive } from 'vue'
  import { negativeKeywordList, adjustNegativeKeyword } from '@/api/advert'
  import { Message, Modal } from '@arco-design/web-vue'
  import { AdStatusHandle, NegativeKeywordMatchType } from '../../types'
  import AddNegativeKeyword from './addNegativeKeyword.vue'
  import { useRouter } from 'vue-router'
  import useAdvertStore from '@/store/modules/advert'

  const props = defineProps({
    searchParams: {
      type: Object,
      default: () => {},
    },
    shopList: {
      type: Array,
      default: () => [],
    },
    level: {
      type: String,
    },
  })
  const emit = defineEmits(['toCampaign'])
  const searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
  })
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  const sortable = reactive({
    sortDirections: ['descend', 'ascend'],
    sorter: true,
  }) as any
  const total = ref(0)
  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([])
  const selectIds = ref([])
  const tableListMap = ref({})
  const addType = ref('add')
  const submitLoading = ref(false)
  const router = useRouter()
  const advertStore = useAdvertStore()
  const statusMap = {
    ENABLED: { name: '已开启', color: 'normal' },
    PAUSED: { name: '已暂停', color: 'normal' },
    ARCHIVED: { name: '已归档', color: 'gray' },
  }
  const showUserDialog = ref(false)
  const selectRows = ref<any>([])
  const tableRef = ref()
  const showAddNegativeKeyword = ref(false)
  const defaultVal = ref()

  const selectColumn = (val: any) => {
    selectIds.value = val
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }
  function getTableListByVal() {
    searchVal.value.pageNum = 1
    getTableList()
  }
  // 获取组合列表数据
  async function getTableList() {
    tableLoading.value = true
    const res: any = await negativeKeywordList({
      ...props.searchParams,
      ...searchVal.value,
    })
    tableLoading.value = false
    tableRef.value.selectAll(false)
    tableList.value = res?.data?.data || []
    total.value = res?.data?.total || 0
    tableListMap.value = {}
    tableList.value.forEach((el) => {
      el.id = el.shopId + el.campaignId + el.keywordId
      tableListMap.value[el.id] = el
    })
  }
  // 排序
  function sorterChange(dataIndex: string, direction: string) {
    if (!direction) {
      searchVal.value.orderItems = null
    } else {
      searchVal.value.orderItems = [
        {
          asc: direction == 'ascend' ? true : false,
          column: dataIndex,
        },
      ]
    }
    getTableList()
  }
  // 批量修改否定关键词状态
  function changeStatus(status: any) {
    if (!selectIds.value.length) {
      return Message.error('请选择否定关键词')
    }
    Modal.confirm({
      title: '调整状态',
      content: `请再次确认，是否${AdStatusHandle[status]}选中的否定关键词`,
      cancelText: '取消',
      okText: '确认',
      onOk: async () => {
        getSelectRows()
        requestUpdataState(selectRows.value, status, AdStatusHandle[status] + '成功')
      },
    })
    showUserDialog.value = true
  }
  //归档否定关键词状态请求
  async function requestUpdataState(list: Array<any>, state: string, msg?: string) {
    let params = list.map((el: any) => {
      return {
        keywordId: el.keywordId,
        adType: el.adType,
        shopId: el.shopId,
      }
    })
    submitLoading.value = true
    const res: any = await adjustNegativeKeyword(params)
    submitLoading.value = false
    if (!res) return
    getTableList()
    if (msg) {
      Message.success(msg)
    }
  }
  // 进入广告组合
  function toPortfolioDetail(row: any) {
    if (props.level) return
    emit('toCampaign', row)
  }
  // 进入活动详情
  function toCampaignDetail(row: any) {
    if (props.level) return
    changeCampaignIn(row)
    advertStore.changeCurrentLevel('campaign')
    router.push('/advert/campaign/campaignDetail')
    emit('toCampaign', row)
  }
  // 进入广告组详情
  function toAdGroupDetail(row: any) {
    if (props.level) return
    changeCampaignIn(row)
    advertStore.changeGroup({
      adGroupId: row.adGroupId,
      adGroupName: row.adGroupName,
    })
    advertStore.changeCurrentLevel('adGroup')
    router.push('/advert/campaign/campaignDetail')
  }
  function changeCampaignIn(row: any) {
    advertStore.changeShop({
      shopId: row.shopId,
      shopName: row.shopName,
      id: row.shopId,
      marketplaceId: row.marketplaceId,
      sellerId: row.sellerId,
    })
    advertStore.changeCampaignIn({
      campaignId: row.campaignId,
      campaignName: row.campaignName,
      adType: row.adType,
      targetingType: 'AUTO',
      state: row.state,
    })
  }
  // 批量添加到其他否定
  function batchAddOtherNegativeKeyword() {
    if (!selectIds.value.length) {
      return Message.error('请选择否定关键词')
    }
    getSelectRows()
    let nameArr = selectRows.value.map((el: any) => el.keywordText)
    defaultVal.value = nameArr.join('\n')
    addType.value = 'addOther'
    showAddNegativeKeyword.value = true
  }
  function addNegativeKeyword() {
    addType.value = 'add'
    defaultVal.value = ''
    showAddNegativeKeyword.value = true
  }
  // 清除选中
  function clearSelect() {
    tableRef.value.selectAll(false)
  }
  function getSelectRows() {
    selectRows.value = []
    selectIds.value.map((id) => {
      selectRows.value.push(tableListMap.value[id])
    })
  }
  defineExpose({ getTableListByVal })
</script>
<style lang="less" scoped>
  .table-gl-con {
    height: 100%;
  }
  .gray {
    color: #999;
  }
  .normal {
    color: var(--color-text-2);
  }
  :deep(.arco-table-sorter) {
    margin-left: 2px;
  }
  .popconfirm-title {
    font-size: 14px;
    margin-bottom: 10px;
  }
</style>
